# -*- coding: utf-8 -*-
from django.http import HttpResponse
from socialbar.constants import DEALSSTATUS, keyFromValue
from socialbar.models import Bar, Deal, Transaction, Price
import logging
import urllib2, urllib
try:
   from urlparse import parse_qs
except ImportError:
   from cgi import parse_qs

couponPrice = 1

def buildRequest():
  isSandbox = True
  if isSandbox == True:
    url = 'https://sandbox.zooz.co/mobile/SecuredWebServlet'
  else:
    url = 'https://app.zooz.com/mobile/SecuredWebServlet'

  req = urllib2.Request(url)
  req.add_header('ZooZ-Unique-ID', 'OhMyBars')
  req.add_header('ZooZ-App-Key', '83ced07b-885a-46d3-a49a-e75eb05d91fa')
  req.add_header('ZooZ-Response-Type', 'NVP')  
  return req 
  
  
def openTrx(request):
  req = buildRequest()
  if 'idPrice' in request.GET:
    idPrice = request.GET['idPrice']
  else:
    idPrice = 1
  price = getPriceFromId(idPrice)
  postData = {'cmd' : 'openTrx',
            'amount' : price,
            'currencyCode' : 'EUR' }
  
  postDataEncoded = urllib.urlencode(postData)
  req.add_data(postDataEncoded)
  res = urllib2.urlopen(req)
  result = res.read()
  results = parse_qs(result)
  if 'token' in results:
    token = results['token'][0]
    token = token.rstrip()
    
    transaction = Transaction()
    transaction.token = token
    transaction.price = getPriceFromId(idPrice)
    transaction.numberOfDeal = getNbCouponFromId(idPrice)
    transaction.status = 'open'
    transaction.user = request.user
    transaction.save()
     
    return HttpResponse( "var data = {'token' : '" + token + "'}")
  else:
    return HttpResponse(result)  

  
def verifyTrx(request):
  req = buildRequest()
  if 'trxId' in request.GET and 'token' in request.GET :
    trxId = request.GET['trxId']
    token = request.GET['token']
  else:
    return HttpResponse('parameters missing.')

  postData = {'cmd' : 'verifyTrx',
              'trxId' : trxId}

  transactions = Transaction.objects.filter(user=request.user,
                         token=token, status='open')
  if len(transactions) == 0:
    return 'Pas de transaction correspondante'

  postDataEncoded = urllib.urlencode(postData)
  req.add_data(postDataEncoded)
  res = urllib2.urlopen(req)
  result = res.read()
  results = parse_qs(result)
  if 'statusCode' in results and results['statusCode'][0] == '0':

    transaction = transactions[0]
    transaction.status = 'end'
    transaction.save()
    nbCoupon = transaction.numberOfDeal

    for i in range(0, nbCoupon):
      deal = Deal()
      deal.user = request.user
      deal.status = keyFromValue(DEALSSTATUS, 'Bought')
      deal.price = 1
      deal.save()
    
    return 'Votre transaction a bien été effectué'
  else:
    return 'Il y a eu un problème avec votre transaction' + result
  
  
  
def getPriceTable():
  prices = Price.objects.all().order_by('price')
  return prices
  
  
def getPriceFromId(idPrice):
  prices = Price.objects.filter(id=idPrice)
  if len(prices) == 0:
    return -1
  else:
    return prices[0].price

  
def getNbCouponFromId(idPrice):
  prices = Price.objects.filter(id=idPrice)
  if len(prices) == 0:
    return -1
  else:
    return prices[0].nbCoupon
  
  
  
  
  
